package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"lyz/cache"
	"lyz/models"
	"lyz/pkg"
	"path/filepath"
	"strconv"
	"time"
)

var err error

type UserController struct {
	beego.Controller
}

type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *UserController) Logic() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "用户名和密码为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	lyz := models.User{
		Username: username,
		Password: pkg.Md5(password),
	}
	err = models.DB.Create(&lyz).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加用户失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "添加用户成功",
		Data: lyz,
	}
	c.ServeJSON()
	return
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "用户名和密码为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	login := "login_user" + username
	count, _ := cache.Rdb.Get(cache.Ctx, login).Int()
	if count >= 3 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "密码错误三次,禁止登录",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	var user models.User
	err = models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "用户不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, login)
		if count == 2 {
			cache.Rdb.Expire(cache.Ctx, login, time.Hour*3)
			c.Data["json"] = Res{
				Code: 0,
				Msg:  "密码错误三次,封禁三个小时",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "密码错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "登陆成功",
		Data: user,
	}
	c.ServeJSON()
	return
}

func (c *UserController) RoleAdd() {
	role_name := c.GetString("role_name")
	if role_name == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "角色名称为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	lyz := models.Role{
		RoleName: role_name,
	}
	err = models.DB.Create(&lyz).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "角色添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "角色添加成功",
		Data: lyz,
	}
	c.ServeJSON()
	return
}

func (c *UserController) NodeAdd() {
	node_name := c.GetString("node_name")
	if node_name == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "权限名为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	lyz := models.Node{
		NodeName: node_name,
	}
	err = models.DB.Create(&lyz).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "权限添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "权限添加成功",
		Data: lyz,
	}
	c.ServeJSON()
	return
}

func (c *UserController) UserRoleAdd() {
	uid, _ := c.GetInt("uid", 0)
	rid, _ := c.GetInt("rid", 0)
	if uid == 0 || rid == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "用户ID和角色ID为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	lyz := models.UserRole{
		Uid: uid,
		Rid: rid,
	}
	err = models.DB.Create(&lyz).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "添加成功",
		Data: lyz,
	}
	c.ServeJSON()
	return
}

func (c *UserController) RoleNodeAdd() {
	rid, _ := c.GetInt("rid", 0)
	nid, _ := c.GetInt("nid", 0)
	if rid == 0 || nid == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "角色ID和权限ID为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	lyz := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err = models.DB.Create(&lyz).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "添加成功",
		Data: lyz,
	}
	c.ServeJSON()
	return
}

func (c *UserController) UserRole() {
	uid, _ := c.GetInt("uid", 0)
	if uid == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "用户ID为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var role []models.Role
	err = models.DB.Table("roles").Joins("left join user_roles on user_roles.rid=roles.id").
		Where("user_roles.uid", uid).
		Find(&role).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: role,
	}
	c.ServeJSON()
	return
}

func (c *UserController) RoleNode() {
	rid, _ := c.GetInt("rid", 0)
	if rid == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "角色id为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var node []models.Node
	err = models.DB.Table("nodes").Joins("left join role_nodes on role_nodes.nid=nodes.id").
		Where("role_nodes.rid", rid).
		Find(&node).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: node,
	}
	c.ServeJSON()
	return
}

func (c *UserController) UserList() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 2)
	f := (page - 1) * size
	var user []models.User
	list := "list_user" + strconv.Itoa(page)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, list).Result()
	var pageData map[string]interface{}
	if cacheJson == "" {
		var count int64
		models.DB.Model(&models.User{}).Count(&count)
		err = models.DB.Offset(f).Limit(size).Find(&user).Error
		if err != nil {
			c.Data["json"] = Res{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		pageData = map[string]interface{}{
			"count": count,
			"user":  user,
		}
		json, _ := json.Marshal(pageData)
		cache.Rdb.Set(cache.Ctx, list, json, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheJson), &pageData)
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: pageData,
	}
	c.ServeJSON()
	return
}

func (c *UserController) UserDetail() {
	id, _ := c.GetInt("id")
	if id == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "用户ID为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var user models.User
	detail := "detail_user" + strconv.Itoa(id)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, detail).Result()
	if cacheJson == "" {
		err = models.DB.Where("id=?", id).First(&user).Error
		if err != nil {
			c.Data["json"] = Res{
				Code: 0,
				Msg:  "展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		json, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, detail, json, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheJson), &user)
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "展示成功",
		Data: user,
	}
	c.ServeJSON()
	return
}

func (c *UserController) Update() {
	file, header, f := c.GetFile("img")
	if f != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "获取文件失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if header.Size > 2*1024*1024 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "大小不能超过2MB",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	ext := filepath.Ext(header.Filename)
	if ext != ".png" && ext != ".jpg" {
		c.Data["json"] = Res{
			Code: 500,
			Data: nil,
			Msg:  "图片格式不正确",
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "上传成功",
		Data: "http://127.0.0.1:8080/" + path,
	}
	c.ServeJSON()
	return
}

func (c *UserController) Add() {
	name := c.GetString("name")
	types := c.GetString("types")
	price := c.GetString("price")
	img := c.GetString("img")
	shop := models.Shop{
		Name:  name,
		Types: types,
		Price: price,
		Img:   img,
	}
	err = models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: shop,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}

func (c *UserController) ShopPage() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	f := (page - 1) * size
	var count int64
	query := models.DB.Model(&models.Shop{})
	var shop []models.Shop
	query.Offset(f).Limit(size).Find(&shop)
	query.Count(&count)
	fxd := make(map[string]interface{})
	fxd["count"] = count
	fxd["shop"] = shop
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: fxd,
	}
	c.ServeJSON()
	return
}
